<template>
    <div class="deviceStateByClassWrapper zy-content">
        <div class="equipmentStatusWra">
            <Row class="comTop" style="padding-bottom: 20px;padding-top: 10px;">
                <Col span="3" >
                    <span class="name">设备状态分布</span>
                    <!-- <strong><em>*</em><span>白班 08:00～20:00</span><span>晚班 20:00～08:00</span><span style="color: #fa5d77;"> 每小时统计一次 </span></strong> -->
                </Col>
                <Col span="4" >
                    <span class="name" style="margin-left:10px">机台号：{{deviceName}}</span>
                </Col>
                <Col span="6" class="tipWrapper" align="left">
                    <span class="tip">
                        <strong class="running"></strong>运行
                    </span>
                    <span class="tip">
                        <strong class="standby"></strong>待机
                    </span>
                    <span class="tip">
                        <strong class="alarm"></strong>告警
                    </span>
                    <span class="tip">
                        <strong class="close"></strong>关机
                    </span>
                </Col>
                <Col span="4" align="center">
                        <RadioGroup v-model="polltype" @on-change='getEchartsList'>
                            <Radio label="6">当班</Radio>
                            <Radio label="4">当日</Radio>
                        </RadioGroup>
                    </Col>
                <Col span="3" align="right">
                    <DatePicker type="date" :placeholder="`${$t('common.selectInfo')}`" :options="options3" v-model="time" @on-change='getEchartsList' :clearable='false'></DatePicker>
                </Col>
                <Col span="4" align="right">
                    <Button type="primary" @click="goBack">返回上一级</Button>
                </Col>
            </Row>
            <!-- <Row class="comTop" style="padding-bottom: 10px;padding-top: 0;"></Row> -->
            <div class="sliceChart" >
                
                <div class="initChart" v-for="(item,index) of devStatusRecords" :key="'after'+index" :style="item | formatStyle">
                    <Tooltip theme="light" :transfer='true'>
                        <div style="height:100%;width:100%;font-size:30px">&nbsp</div>
                        <div slot="content">
                            <p>{{item.statusName}}</p>
                            <p>开始时间：{{item.startTime}}</p>
                            <p>结束时间：{{item.endTime}}</p>
                        </div>
                    </Tooltip>
                </div>
            </div>
        </div>
        <div class="histogram" id="openRate" v-resize="resize">

        </div>
        <div class="histogram" id="yieldAnalysis">

        </div>
        <div class="histogram" id="beatStatistics">

        </div>
    </div>
</template>
<script>
    let moment = window.$this.moment;
    import * as echarts from 'echarts';
    export default {
        name: 'deviceStateByClass',
        components: {},
        props:['detailId','deviceName'],
        data() {
            return {
                polltype:'6',
                options3: {
                    disabledDate (date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                countDate: '2018-01-01',
                devStatusRecords: [],
                deviceId:this.$route.query.id,
                queryTime:'',
                time:moment(new Date()).format('YYYY-MM-DD'),
                openRateKeyList:[],
                openRateValueList:[],
                // detailId:'SQ87'
            }
        },
        created(){
            if(this.$route.query.date){
                this.queryTime = this.$route.query.date
            } else {
                this.queryTime = moment(new Date()).format('YYYY-MM-DD')
            }
        },
        directives: {  // 使用局部注册指令的方式
            resize: { // 指令的名称
                bind (el, binding) { // el为绑定的元素，binding为绑定给指令的对象
                    let width = '', height = '';
                    function isReize () {
                    const style = document.defaultView.getComputedStyle(el);
                    if (width !== style.width || height !== style.height) {
                        binding.value();  // 关键
                    }
                    width = style.width;
                    height = style.height;
                    }
                    el.__vueSetInterval__ = setInterval(isReize, 500);
                },
                unbind (el) {
                    clearInterval(el.__vueSetInterval__);
                }
            }
        },
        mounted() {
            this.getEchartsList()
        },
        methods: {
            getEchartsList(){
                this.getOpenRate()
                this.getProductBeat()
                this.getDeviveStatus()
            },
            goBack(){
                this.$emit('updateShowDetailF')
            },
            getOpenRate(){
                this.axios({
                    method: 'get',
                    url: '/dms/dmsDevice/startRateStatistic',
                    params: {
                        deviceId:this.detailId,
                        time:moment(this.time).format('YYYY-MM-DD'),
                        type:this.polltype
                    }
                }).then(res => {
                    if(res.code === 200){
                       this.openRateChart(Object.keys(res.data),Object.values(res.data));
                    }else{
                        this.$Message.warning(({content:res.msg,duration:6,closable:true}));
                    }
                })
            },
            getProductBeat(){
                this.axios({
                    method: 'get',
                    url: '/dms/chart/deviceYield',
                    params: {
                        deviceId:this.detailId,
                        timeType:this.polltype,
                        dateTime:moment(this.time).format('YYYY-MM-DD')
                    }
                }).then(res => {
                    if(res.code === 200){
                        let beatKey=res.data.beatHistory.map((item)=>{
                            return item.startTime.substring(11,16)+'~'+item.endTime.substring(11,16);
                        })
                        let beatValue1=res.data.beatHistory.map((item)=>{
                            return item.yield;
                        })
                        let beatValue2=res.data.beatHistory.map((item)=>{
                            return item.beat;
                        })
                        let yieldList = res.data.yieldHistory.map((item)=>{
                            return [item.time,item.totalYield];
                        })
                       this.beatStatisticsChart(beatKey,beatValue1,beatValue2,Math.max.apply(null,beatValue1),Math.max.apply(null,beatValue2));
                       this.yieldAnalysisChart(yieldList);
                    }else{
                        this.$Message.warning(({content:res.msg,duration:6,closable:true}));
                    }
                })
            },
            resize () {
                echarts.init(document.getElementById("beatStatistics")).resize();
                echarts.init(document.getElementById("yieldAnalysis")).resize();
                echarts.init(document.getElementById("openRate")).resize();
            },
            openRateChart(key,value) {
                let myChart = echarts.init(document.getElementById("openRate"));
                myChart.setOption({
                    title: {
                        text: '设备开动率',
                        top: "8%",
                        left: '1%',
                    },
                    tooltip: {
                        trigger: 'axis',
                        position: function (pt) {
                            return [pt[0], '10%'];
                        }
                    },
                    grid: {
                        //图的边距
                        top: '24%', //左边距
                        left: '8%', //左边距
                        right: '10%', //右边距
                        bottom: '2%', //下边距
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: key,
                        axisTick: {
                            show: false
                        },
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '开动率',
                            data: value,
                            type: 'line'
                        }
                    ]
                });
                window.addEventListener("resize", function () {
                    myChart.resize(); //myChart指自己定义的echartsDom对象
                });
            },
            beatStatisticsChart(beatKey,beatValue1,beatValue2,max1,max2){
                let myChart = echarts.init(document.getElementById("beatStatistics"));
                myChart.setOption({
                    title: {
                        text: '设备生产节拍',
                        top: "8%",
                        left: '1%',
                    },
                    
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                        }
                    },
                    grid: {
                        //图的边距
                        top: '30%', //左边距
                        left: '8%', //左边距
                        right: '10%', //右边距
                        bottom: '2%', //下边距
                        containLabel: true
                    },
                    legend: {
                        data: ['节拍', '小时产量'],
                        top:'2%',
                        right:'8%'
                    },
                    xAxis: [
                        {
                        type: 'category',
                        data: beatKey,
                        axisPointer: {
                            type: 'shadow'
                        },
                        axisTick: {
                            show: false
                        },
                        
                        }
                    ],
                    yAxis: [
                        {
                        type: 'value',
                        name: '单位:件',
                        min: 0,
                        max: max1,
                        axisLabel: {
                            formatter: '{value}'
                        }
                        },
                        {
                        type: 'value',
                        name: '单位:秒/件',
                        min: 0,
                        max: max2,
                        axisLabel: {
                            formatter: '{value}'
                        }
                        }
                    ],
                    series: [
                        {
                            name: '小时产量',
                            type: 'bar',
                            tooltip: {
                                valueFormatter: function (value) {
                                    return value + '件';
                                }
                            },
                            data: beatValue1
                        },
                        {
                            name: '节拍',
                            type: 'line',
                            yAxisIndex: 1,
                            tooltip: {
                                valueFormatter: function (value) {
                                return value + '秒/件';
                                }
                            },
                            data: beatValue2
                        }
                    ]
                });
                window.addEventListener("resize", function () {
                    myChart.resize(); //myChart指自己定义的echartsDom对象
                });
            },
            yieldAnalysisChart(arr) {
                let myChart = echarts.init(document.getElementById("yieldAnalysis"));
                myChart.setOption({
                    title: {
                        text: '设备产量爬坡',
                        top: "8%",
                        left: '1%',
                    },
                     tooltip: {
                        trigger: 'axis',
                        position: function (pt) {
                        return [pt[0], '10%'];
                        }
                    },
                    grid: {
                        //图的边距
                        top: '24%', //左边距
                        left: '8%', //左边距
                        right: '10%', //右边距
                        bottom: '2%', //下边距
                        containLabel: true
                    },
                    xAxis: {
                        type: 'time',
                        splitNumber: new Date().getHours()>=12?12:'',
                        axisTick: {
                            show: false
                        },
                        axisLabel: {
                            formatter: function (val) {
                                let date= new Date(val)
                                let hours = date.getHours()<10?'0'+date.getHours():date.getHours()
                                let minute = date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes()
                                let texts=[hours,minute]
                                return texts.join(":")
                            }
                            
                        }
                    },
                    yAxis: {
                        type: 'value',
                    },
                    series: [
                        {
                            name: '产量',
                            type: 'line',
                            data: arr
                        }
                    ]
                });
                window.addEventListener("resize", function () {
                    myChart.resize(); //myChart指自己定义的echartsDom对象
                });
            },
            getDeviveStatus(){
                this.axios({
                    method: 'get',
                    url: '/dms/chart/state',
                    params: {
                        deviceId:this.detailId,
                        timeType:this.polltype,
                        dateTime:moment(this.time).format('YYYY-MM-DD')
                    }
                }).then(res => {
                    if (res.code === 200) {
                        let data = res.data;
                        let start = ''
                        let end = ''
                        if(data&&data.length>0){
                            start = moment(data[0].startTime)
                            end = moment(data[data.length-1].endTime)
                        }
                        let stateList = res.data.map((item)=>{
                            let widthValue = (moment(item.endTime)-moment(item.startTime))/(end-start)*100
                            let statusName = ''
                            switch (item.state) {
                                case 1:
                                    statusName = '运行';
                                    break;
                                case 2:
                                    statusName = '待机';
                                    break;
                                case 4:
                                    statusName = '关机';
                                    break;
                                case 5:
                                    statusName = '告警';
                                    break;
                                default:
                                    statusName = '关机';
                            }
                            return {...item,'Width':widthValue,"statusName":statusName};
                        })
                        this.devStatusRecords = stateList
                    } else {
                        this.$Message.warning({content: res.message, duration: 6, closable: true});
                    }
                })
            },

        },
        filters: {
            formatStyle (item) {
                let style = ''
                switch (item.state) {
                    case 1:
                        style = 'background: #2bd2b5;';
                        break;
                    case 2:
                        style = 'background: #fab638;';
                        break;
                    case 4:
                        style = 'background: #777777;';
                        break;
                    case 5:
                        style = 'background: #f96e85;';
                        break;
                    default:
                        style = 'background: #777777;';
                }
                return 'width: '+ item.Width +'%;'+style;
            },
            filterClass (item) {
                let name = 'close';
                switch (item.statusNbr) {
                    case 1:
                        name = 'running';
                        break;
                    case 2:
                        name = 'standby';
                        break;
                    case 6:
                        name = 'alarm';
                        break;
                    default:
                        name = 'close';
                }
                return name;
            },
        }
    }
</script>

<style lang="scss" scoped>
    .deviceStateByClassWrapper{
        .debug{
            background: #4299ff;
        }
        .close{
            background: #777777;
        }
        .alarm{
            background: #f96e85;
        }
        .standby{
            background: #fab638;
        }
        .running{
            background: #2bd2b5;
        }
        .histogram {
            width: 100%;
            border-top: 5px solid #f0f1f7;
            height: 230px;
            background-color: #fff;
        }
        .equipmentStatusWra{
            padding: 0 25px 25px 25px;
            background: #fff;
            margin-top: 15px;
            min-height: 130px;
            .comTop{
                padding: 20px 0 50px 0;
                line-height: 37px;
                .ivu-date-picker{
                    display:inline-block !important;
                }
                .name{
                    color: rgb(70,70,70);
                    vertical-align: middle;
                    font-size: 18px;
                    font-weight: bolder;
                }
                strong{
                    vertical-align: middle;
                    margin-left: 20px;
                    font-weight: normal;
                    width: 340px;
                    color: #777777;
                    display: inline-block;
                    em{
                        color: #fa5f79;
                        vertical-align: middle;
                        margin-right: -19px;
                    }
                    span{
                        margin-left: 20px;
                        color: #999999;
                    }
                }
                .tipWrapper{
                    .tip{
                        display: inline-block;
                        margin-left: 30px;
                        strong{
                            width: 8px;
                            height: 8px;
                            display: inline-block;
                            border-radius: 50%;
                            margin-right: 15px;
                        }
                    }
                }
                .seeButton{
                    text-align: right;
                    i{
                        margin-right: -10px;
                        vertical-align: middle;
                    }
                }
            }
            .sliceChart{
                
                height: 40px;
                width: 100%;
                // background: #2bd2b5;
                // border: 1px solid #999999;
                position: relative;
                .initChart{
                    height: 100%;
                    float: left;
                    z-index: 1;
                    cursor: pointer;
                }
                .initChart:hover {
                    overflow: hidden;
                    transform: scale(101%, 110%);
                    -webkit-transform: scale(101%, 110%);
                    -moz-transform: scale(101%, 110%);
                }
            }
        }
    }
</style>
<style lang="scss">
.deviceStateByClassWrapper{
    .ivu-tooltip{
        display:block;    
        height: 40px;
        width: 100%;
        z-index: 100;
    }
    .ivu-btn>span{
        vertical-align:baseline
    }
  }
</style>

